package com.lemon.smartsafety.ui.activity.safe.inspection;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.datacoll.BuildListItemEvent;
import com.lemon.smartsafety.entity.event.datacoll.KeyWordEvent;
import com.lemon.smartsafety.entity.event.datacoll.PopupEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.BindNfcEvent;
import com.lemon.smartsafety.entity.safe.company.BindQrcodeEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingGroupVo;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafety.interfac.BackInterface;
import com.lemon.smartsafety.tag.BaseTAG;
import com.lemon.smartsafety.tag.DefaultCode;
import com.lemon.smartsafetynew.ui.activity.base.BaseSearchFragmentActivity;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingCheckItemBindNfcActivity;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingCheckItemPositionActivity;
import com.lemon.smartsafety.ui.activity.safe.nfcandqrcode.CodeInspectionStepOneActivity;
import com.lemon.smartsafety.ui.adapter.safe.nfcorqrcode.BuildItemAdapter;
import com.lemon.smartsafety.ui.fragment.safe.data.BuildingCheckItemListFragment;
import com.lemon.smartsafety.ui.fragment.safe.data.BuildingListFragment;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.pop.PopList;
import com.lemon.smartsafetynew.ui.activity.qrcode.CodeUtils;
import com.lemon.smartsafetynew.ui.activity.qrcode.QRcodeActivity;
import com.lemon.smartsafety.entity.event.nfcorqrcode.BuildItemSelectEvent;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.permission.EasyPermissions;

/**
 * Created by Cooliean on 16/1/24.
 * 《安全巡查》【建筑列表】
 */
public class SafeInspectionBuildingListActivity extends BaseSearchFragmentActivity {
    private BuildingListFragment mFragment;
    private CompanyInfo mCompanyInfo;

    @Bind(R.id.tv_tip)
    TextView tvTip;

    @Bind(R.id.tv_tab)
    TextView tvTab;
    @Bind(R.id.line_tab)
    LinearLayout lineTab;


    private List<SelectDataI> mGroupItems = new ArrayList<>();
    private String mKeyWord = "";


    private List<CompanyBuildingGroupVo> resultBuildItemList;
    private PopList popList;
    private BuildItemAdapter buildItemAdapter;

    //是否是POP请求的data
    private boolean isPopData = false;


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("mCompanyInfo", mCompanyInfo);
        outState.putSerializable("mGroupItems", (Serializable) mGroupItems);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mCompanyInfo = (CompanyInfo) savedInstanceState.getSerializable("mCompanyInfo");
            mGroupItems = (List<SelectDataI>) savedInstanceState.getSerializable("mGroupItems");
        }
    }

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        tvTip.setVisibility(View.VISIBLE);
        tvTip.setText(R.string.safe_inspection_tip);

        lineTab.setVisibility(View.VISIBLE);
        tvTab.setText("全部类型");

        resultBuildItemList = new ArrayList<>();
        SafeDataServices.init().getBuildingGroupList();

    }

    @Override
    public Fragment getFragment() {
        mKeyWord = "";
        return getFragment(null);
    }


    public Fragment getFragment(String text) {
        Bundle bundle = new Bundle();
        if (null != text) {
            bundle.putString(BundleKey.KEY_WORD, text);
        }
        bundle.putSerializable(BundleKey.COMPANY_INFO, mCompanyInfo);
        bundle.putBoolean(BundleKey.IS_SAFE_INSPECTION, true);
        mFragment = BuildingListFragment.newInstance();
        mFragment.setArguments(bundle);
        mKeyWord = StringUtils.nullValue(text);
        return mFragment;
    }

    @Override
    public int getSearchHintRes() {
        return R.string.search_common_hit;
    }

    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.safe_title);
    }

    @Override
    public boolean onQueryTextSubmit(String queryText) {
        queryText = StringUtils.nullValue(queryText);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.main_content, getFragment(queryText), getFragment(queryText).getClass()
                        .getName())
                .commit();
        return super.onQueryTextSubmit(queryText);
    }


    @Subscribe
    public void onEventMainThread(BuildListItemEvent event) {
        if (BuildingListFragment.class.getName().equals(event.getTag())) {
            if (mCompanyInfo == null) {
                mHUDUtil.showErrorTip(getString(R.string.params_error));
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, event.getData());
            bundle.putSerializable(BundleKey.COMPANY_INFO, mCompanyInfo);
            bundle.putBoolean(BundleKey.IS_SAFE_INSPECTION, true);
            UIHelper.showActivity(SafeInspectionBuildingListActivity.this, bundle, BuildingCheckItemPositionActivity.class);
//            if (mSharedPreferencesHelper.isCloseFireListView()) {
//                callFinish();
//            }
        }
    }

    @OnClick({R.id.line_tab})
    public void onButtonClick(View v) {
        switch (v.getId()) {
            case R.id.line_tab:
                isPopData = true;
                if (CommonUtil.listIsEmpty(resultBuildItemList)) {
                    SafeDataServices.init().getBuildingGroupList();
                } else {
                    showPopState();
                }
                break;
            default:
                break;
        }
    }

    private void showPopState() {
        isPopData = false;
        if (buildItemAdapter == null) {
            buildItemAdapter = new BuildItemAdapter(this, resultBuildItemList);
            buildItemAdapter.setCallBackInterfaceInt(new BackInterface.CallBackInterfaceInt() {
                @Override
                public void callBackFunction(int item) {
                    buildItemAdapter.setStrSelect(resultBuildItemList.get(item).getGroupName());
                    buildItemAdapter.notifyDataSetChanged();
                    tvTab.setText(resultBuildItemList.get(item).getGroupName());
                    popList.dismiss();

                    AppService.getBus().post(new BuildItemSelectEvent(resultBuildItemList.get(item)));

                }
            });
        }

        if (popList == null) {
            popList = new PopList();
        }
        popList.showPop(this, lineTab, buildItemAdapter);


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconEnable(menu, true);
        boolean menuResult = super.onCreateOptionsMenu(menu);
        //getMenuInflater().inflate(R.menu.menu_filter, menu);
     getMenuInflater().inflate(R.menu.menu_qrcode, menu);
      getMenuInflater().inflate(R.menu.menu_nfc, menu);

        return menuResult;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    /*    if (item.getItemId() == R.id.action_filter) {
            showPopWindow();
        }*/
        if (item.getItemId() == R.id.action_qrcode) {
            if (getOpenCameraEasyPermissions()) {
                startQrcode();
            }
        }
        if (item.getItemId() == R.id.action_nfc) {
            startNfc();
        }


        return super.onOptionsItemSelected(item);
    }

    private void startNfc() {
        Bundle bundle = new Bundle();
        bundle.putString(BaseTAG.COMMON_BASE_TAG, BuildingCheckItemListFragment.class.getName());
        UIHelper.showActivity(this, bundle, BuildingCheckItemBindNfcActivity.class);
    }


    private void startQrcode() {
        try {
            //Intent intent = new Intent(this, CaptureActivity.class);
            Intent intent = new Intent(this, QRcodeActivity.class);
            startActivityForResult(intent, DefaultCode.REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return 不知为何 华为手机申请摄像头权限会崩溃
     */
    private boolean getOpenCameraEasyPermissions() {

        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            return true;
        } else {
            ToastUtil.show("请允许摄像头权限");
            return false;
        }

    }


    /**
     * 绑定NFC的返回通知
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BindNfcEvent event) {
        if (BuildingCheckItemListFragment.class.getName().equals(event.getTag())) {
            if (!CommonUtil.strIsEmpty(event.getCode())) {
                LogUtils.LOGE("巡查NFC:" + event.getCode());
                Bundle bundle = new Bundle();
                bundle.putString(BaseTAG.COMMON_BASE_TAG, event.getCode());
                UIHelper.showActivity(this, bundle, CodeInspectionStepOneActivity.class);
            }
        }
    }


    /**
     * 绑定NFC的返回通知
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BindQrcodeEvent event) {
        if (BuildingCheckItemListFragment.class.getName().equals(event.getTag())) {
            if (!CommonUtil.strIsEmpty(event.getCode())) {
                LogUtils.LOGE("巡查二维码:" + event.getCode());
                Bundle bundle = new Bundle();
                bundle.putString(BaseTAG.COMMON_BASE_TAG, event.getCode());
                UIHelper.showActivity(this, bundle, CodeInspectionStepOneActivity.class);
            }
        }
    }


    public void showPopWindow() {
        if (mGroupItems.isEmpty()) {
            SafeDataServices.init().getBuildingGroupList();
        } else {
            postPopEvent();
        }
    }

    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.BUILDING_GROUP_LIST.equals(event.getTag())) {
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    try {
                        resultBuildItemList.clear();
                        resultBuildItemList.add(new CompanyBuildingGroupVo("全部类型"));
                        List<CompanyBuildingGroupVo> dataList= (List<CompanyBuildingGroupVo>) event.getObj();
                        resultBuildItemList.addAll(dataList);
                    } catch (Exception e) {
                        e.printStackTrace();
                        resultBuildItemList.clear();
                    }

                    if (isPopData) {
                        showPopState();
                    }

               /*     List<SelectDataI> dataIs = (List<SelectDataI>) event.getObj();
                    if (null != dataIs && dataIs.size() != 0) {
                        mGroupItems.clear();
                        mGroupItems.addAll(dataIs);
                    }*/
                }
                //postPopEvent();
            }
        }
    }

    private void postPopEvent() {
        PopupEvent appEvent = new PopupEvent();
        appEvent.setKeyword(mKeyWord);
        appEvent.setData(mGroupItems);
        AppService.getBus().post(appEvent);
    }

    @Subscribe
    public void onEventMainThread(KeyWordEvent event) {
        mGroupItems.clear();
        mGroupItems.addAll(event.getData());
        mKeyWord = StringUtils.nullValue(event.getKeyword());
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == DefaultCode.REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    LogUtils.LOGE("解析结果:" + result);
                    AppService.getBus().post(new BindQrcodeEvent(result, BuildingCheckItemListFragment.class.getName()));
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtils.toastMsg("解析二维码失败");
                }
            }
        }

    }
}
